package com.qf.controller;

import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.util.JacksonUtil;
import com.qf.util.ResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/admin/profile")
public class AdminProfileController {

    @Autowired
    private AdminService adminService;

    //oldPassword: "987", newPassword: "987654", newPassword2: "987654"
    @RequiresUser
    @PostMapping("password")
    public Object password(@RequestBody String json){
        String oldPassword = JacksonUtil.parseString(json, "oldPassword");
        String newPassword = JacksonUtil.parseString(json, "newPassword");
        String newPassword2 = JacksonUtil.parseString(json, "newPassword2");

        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
        System.out.println(admin);
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        if (StringUtils.isEmpty(oldPassword)){
            return ResponseUtil.fail(-1,"原密码不能为空");
        }
        if (!bCryptPasswordEncoder.matches(oldPassword, admin.getPassword())){
            return ResponseUtil.fail(-1,"原密码不正确");
        }
        if (StringUtils.isEmpty(newPassword)){
            return ResponseUtil.fail(-1,"新密码不能为空");
        }
        if (!newPassword.equals(newPassword2)){
            return ResponseUtil.fail(-1,"两次密码不一致");
        }
        newPassword = bCryptPasswordEncoder.encode(newPassword);
        adminService.updatePassword(admin.getId(),newPassword);
        subject.logout();

        return ResponseUtil.ok();
    }




}
